package com.zhangyu.shadow.ec.pay;

import android.app.Activity;
import android.os.AsyncTask;

import com.alipay.sdk.app.PayTask;
import com.zhangyu.shadow.core.ui.loader.ShadowLoader;
import com.zhangyu.shadow.core.util.log.ShadowLogger;

/**
 * @author zhangyu
 * @date 2017/11/22
 */

public class PayAsyncTask extends AsyncTask<String, Void, String> {
    private static final String TAG = "PayAsyncTask";
    private final Activity mActivity;
    private final IPayResultListener mIPayResultListener;
    //订单支付成功
    private static final String AL_PAY_STATUS_SUCCESS = "9000";
    //订单处理中
    private static final String AL_PAY_STATUS_PAYING = "8000";
    //订单支付失败
    private static final String AL_PAY_STATUS_FAIL = "4000";
    //用户取消
    private static final String AL_PAY_STATUS_CANCEL = "6001";
    //支付网络错误
    private static final String AL_PAY_STATUS_CONNECT_ERROR = "6002";

    public PayAsyncTask(Activity activity, IPayResultListener iPayResultListener) {
        mActivity = activity;
        mIPayResultListener = iPayResultListener;
    }

    @Override
    protected String doInBackground(String... params) {
        final String aliPaySign = params[0];
        final PayTask payTask = new PayTask(mActivity);
        return payTask.pay(aliPaySign, true);
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        ShadowLoader.stopLoading();
        final PayResult payResult = new PayResult(result);
        //支付宝返回此次支付结果及加签，用公钥做验签
        final String resultInfo = payResult.getResult();
        final String resultStatus = payResult.getResultStatus();
        ShadowLogger.e(TAG + "resultInfo", resultInfo);
        ShadowLogger.e(TAG + "resultStatus", resultStatus);
        switch (resultStatus) {
            case AL_PAY_STATUS_SUCCESS:
                if (mIPayResultListener != null) {
                    mIPayResultListener.onPaySuccess();
                }
                break;
            case AL_PAY_STATUS_FAIL:
                if (mIPayResultListener != null) {
                    mIPayResultListener.onPayFailed();
                }
                break;
            case AL_PAY_STATUS_PAYING:
                if (mIPayResultListener != null) {
                    mIPayResultListener.onPaying();
                }
                break;
            case AL_PAY_STATUS_CANCEL:
                if (mIPayResultListener != null) {
                    mIPayResultListener.onPayCancel();
                }
                break;
            case AL_PAY_STATUS_CONNECT_ERROR:
                if (mIPayResultListener != null) {
                    mIPayResultListener.onPayConnectError();
                }
                break;
            default:
                break;
        }
    }
}
